package com.cqgcxy.shopping.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqgcxy.shopping.service.UserService;
import com.cqgcxy.shopping.common.CommException;
import com.cqgcxy.shopping.domain.User;
@WebServlet(urlPatterns={"/user/changepwd.do"})
public class ChangePwdServlet extends HttpServlet {

	private static final long serialVersionUID = 975944926265062978L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private UserService userService=new UserService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.debug("开始执行dopost方法");
		try {
			//获得参数
			String usercode = req.getParameter("usercode");
			String password = req.getParameter("password");
			String newpassword = req.getParameter("newpassword");
			String confirm = req.getParameter("confirm");
			logger.debug("{}---{}",password,newpassword);
			if(password==null||password.trim().length()<=0) {
				throw new CommException("密码不能为空！");
			}
			if(newpassword==null||newpassword.trim().length()<=0) {
				throw new CommException("新密码不能为空！");
			}
			if(newpassword.equals(password)) {
				throw new CommException("新密码不能和旧密码相同！");
			}
			if(!confirm.equals(newpassword)) {
				throw new CommException("新密码不相同！");
			}
			
			//参数封装为对象
			User user=new User();
			user.setUsercode(usercode);
			user.setPassword(password);
			user.setNewPassword(newpassword);
			//5.调用业务方法
			userService.changepwd(user);
			logger.debug("{}",user.getUsercode());
			resp.sendRedirect(req.getContextPath()+"/member/personal.jsp");//请求重定向
			logger.info("修改成功！");
		}catch (Exception e) {
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/changepwd.jsp").forward(req, resp);//转发
			logger.debug("密码修改失败：{}",e.getMessage());
		}
		}
}
